package com.yuchen.ishop.web.app;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yuchen.ishop.entity.SellerXiaoer;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yuchen.core.cache.J2CacheUtils;
import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.entity.Buyer;
import com.yuchen.ishop.entity.Seller;
import com.yuchen.ishop.service.login.LoginRestClient;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.jaxrs.Responses;
import com.yuchen.utils.CookieUtils;
import com.yuchen.utils.RandomUtils;
import com.yuchen.utils.fastjson.JsonUtils;
import com.yuchen.utils.security.Base64Utils;


/**
 * 登录
 */
@Controller
public class LoginAction extends BaseAction {

    private final static Logger LOG = Logger.getLogger(LoginAction.class);

    @Autowired
    private LoginRestClient loginRestClient;


    @RequestMapping(value = "/buyerLogin")
    public String buyerLogin(String account,String password,String returnUrl,HttpServletRequest request,RedirectAttributes redirectAttributes,HttpServletResponse response)throws Exception {
    	if(doCRSF(request)){
            redirectAttributes.addFlashAttribute("flash",errorJson("非法CRSF请求！"));
            return "redirect:/error.htm";
        }
    	if(StringUtils.isBlank(account) || StringUtils.isBlank(password)){
            return goLogin(1,redirectAttributes,returnUrl);
        }
    	Responses r = loginRestClient.buyerLogin(account, password);
    	Buyer buyer = JsonUtils.parseObject(r.getJson(),Buyer.class);
        if(buyer==null || buyer.getId()==null || buyer.getSalt()==null){
            return goLogin(1,redirectAttributes,returnUrl);
        }
        CookieUtils.addCookie(Gobals.COOKIE_ID,base64UserInfo("buyer", buyer.getId(), buyer.getSalt()),response);
       /* J2CacheUtils.evict(Gobals.COOKIE_ID,"buyer_"+buyer.getId());
        J2CacheUtils.set(Gobals.CACHE_USERINFO,"buyer_"+buyer.getId(),buyer);*/
        if(StringUtils.isNotBlank(returnUrl)){
            return "redirect:"+returnUrl;
        }
        return "redirect:/";
    }

    @RequestMapping(value = "/sellerLogin",method = RequestMethod.POST)
    public String sellerLogin(String account,String password,String type,String returnUrl,HttpServletRequest request,RedirectAttributes redirectAttributes,HttpServletResponse response)throws Exception {
        //
        if(doCRSF(request)){
            redirectAttributes.addFlashAttribute("flash",errorJson("非法CRSF请求！"));
            return "redirect:/error.htm";
        }
        if(StringUtils.isBlank(account) || StringUtils.isBlank(password)){
            return goLogin(2,redirectAttributes,returnUrl);
        }
        if("seller".equals(type)){
            Responses r = loginRestClient.sellerLogin(account, password);
            if(!r.isStatus()){
                return goLogin(2,redirectAttributes,returnUrl);
            }
            Seller seller = JsonUtils.parseObject(r.getJson(),Seller.class);
            if(seller==null || seller.getId()==null || seller.getSalt()==null){
                return goLogin(2,redirectAttributes,returnUrl);
            }
            CookieUtils.addCookie(Gobals.COOKIE_ID,base64UserInfo("seller", seller.getId(), seller.getSalt()), response);
           /* J2CacheUtils.evict(Gobals.COOKIE_ID,"seller_"+seller.getId());
            J2CacheUtils.set(Gobals.CACHE_USERINFO,"seller_"+seller.getId(),seller);*/
        }else{
            Responses r = loginRestClient.xiaoerLogin(account, password);
            if(!r.isStatus()){
                return goLogin(2,redirectAttributes,returnUrl);
            }
            SellerXiaoer sellerXiaoer = JsonUtils.parseObject(r.getJson(),SellerXiaoer.class);
            if(sellerXiaoer==null || sellerXiaoer.getId()==null || sellerXiaoer.getSalt()==null){
                return goLogin(2,redirectAttributes,returnUrl);
            }
            CookieUtils.addCookie(Gobals.COOKIE_ID,base64UserInfo("xiaoer",sellerXiaoer.getId(),sellerXiaoer.getSalt()),response);
           /* J2CacheUtils.evict(Gobals.COOKIE_ID,"xiaoer_"+sellerXiaoer.getId());
            J2CacheUtils.set(Gobals.CACHE_USERINFO,"xiaoer_"+sellerXiaoer.getId(),sellerXiaoer);*/
        }
        if(StringUtils.isNotBlank(returnUrl)){
            return "redirect:"+returnUrl;
        }
        return "redirect:/my.htm";
    }


    private String goLogin(int tab,RedirectAttributes redirectAttributes,String returnUrl){
        redirectAttributes.addFlashAttribute("flash",errorJson("用户名或密码错误！"));
        redirectAttributes.addFlashAttribute("tab",tab);
        if(StringUtils.isNotBlank(returnUrl)){
            return "redirect:/goLogin.htm?returnUrl="+returnUrl;
        }
        return "redirect:/goLogin.htm";
    }

    private String base64UserInfo(String role,Long userId,String salt){
        StringBuilder ishopid = new StringBuilder();
        ishopid.append(userId).append("@").append(role).append("@").append(RandomUtils.randomAll(10)).append(salt);
        return Base64Utils.encodeBase64(ishopid.toString());
    }
}

